﻿/**
 * 实现自动登录功能
 */
(function(){
	var	domainList = [],
		time = 1,//由于读取内容是从内存读取，所以减少超时时间
		timeoutHandler = null,
		loginTimeoutHandler = null,
		flag_skip = true,
		clk_flag = true,
		tempDomainNum = 0,
		rd = "",
		web_qid = '',
		primaryStation = false,
		oneUnit = 134,
		number = 0,
		tempN = 0,
		acc_msg = "快速登录失败，请使用其他方式登录",
		acc_msg_web = "您选择的帐号已失效，请检查该帐号是否已经退出",
		timerId, startTime, frameTime = 13, dur = 1 * 1000,
		s_flag = false,
		dire,mleft,src,obj = g('loginUserList'),
		iskeepalive = 1;
	src = queryUrl(location.href).src ? queryUrl(location.href).src : 'pcw_i360';
	/*******点击下次自动登录*****/
	if (displayType!="newpic") {
		g('loginCheckBox').onclick = function(e){
			var span = g('iskeepalive');
			var spanClassName = span.className;
			if(spanClassName.toString().indexOf("checked")>-1){
				span.className = "checkbox quick-login-common-bg";
				iskeepalive = 0;
			}else{
				span.className = "checkbox checked quick-login-common-bg";
				iskeepalive = 1;
			}
		}
	}
	
	
	/*********获取业务标示**********/
	
	function queryUrl(url){
		var queryStr = location.search.substring(1).split('&'),oneQueryStr,args = {};
		for(var i in queryStr){
			oneQueryStr = queryStr[i].split('=');
			if(oneQueryStr[0]&&oneQueryStr[1]&&oneQueryStr[0]=="src"){
				args[oneQueryStr[0]] = (oneQueryStr[1]||'').replace(/[><'"{}]/g, '');
			}
		}
		return args;
	}
	
	/******通知父页面********/
	function noticeParent(status, isGetStauts){
		var callback = null;
		/*******判断是否非法*****/
		// status 0表示登录成功，1表示查找到了帐号，2为没查到帐号和其他情况
		nextUrl = (nextUrl||'').replace(/[><'"{}]/g, '');

		if(isGetStauts) {
			callback = func;
		}else {
			callback = 'QHPass.ptLogin';
		}
		//us参数只对获取用户个数有用
		if(nextUrl&&requestValid!=0){
			g('ifr_getmsg').src= nextUrl +"?fun=parent.parent."+callback+"&s="+status+"&us=0";
		}else if(nextUrl.indexOf("document")>-1||
			nextUrl.indexOf("location")>-1||
			nextUrl.indexOf("alert")>-1||
			nextUrl.indexOf("window")>-1){
		}else{
			g('ifr_getmsg').src= nextUrl +"?fun=parent.parent."+callback+"&s="+status+"&us=0";
		}
		
	}

	if(requestValid==0){
		noticeParent(2);
		return;
	}
	
	var	forEach  =  function(arr, callback, pThis) {
		for (var i = 0, len = arr.length; i < len; i++) {
			if (i in arr) {
				callback.call(pThis, arr[i], i, arr);
							}
				}
	},loadJs = function(url, onsuccess, options) {
		options = options || {};
		var head = document.getElementsByTagName('head')[0]
				|| document.documentElement, script = document
				.createElement('script'), done = false;
		script.src = url;
		if (options.charset) {
			script.charset = options.charset;
		}
		script.onerror = script.onload = script.onreadystatechange = function() {
			if (!done
					&& (!this.readyState || this.readyState == "loaded" || this.readyState == "complete")) {
				done = true;
				onsuccess && onsuccess();
				script.onerror = script.onload = script.onreadystatechange = null;
				head.removeChild(script);
			}
		};
		head.insertBefore(script, head.firstChild);
	}, loadJsonp = (function() {
		var seq = new Date() * 1;
		return function(url, onsuccess, options) {
			options = options || {};
			var funName = "QiUserJsonP" + seq++, callbackReplacer = options.callbackReplacer || /%callback%/ig;
			window[funName] = function(data) {
				onsuccess && onsuccess(data);
				window[funName] = null;
			};
			if (callbackReplacer.test(url))
				url = url.replace(callbackReplacer, funName);
			else {
				url += (/\?/.test(url) ? "&" : "?") + "callback="
						+ funName;
			}
			loadJs(url, null, options);
		};
	}());
	
	timeoutHandler = setTimeout(function(){
	//获取用户长度和登录逻辑都会进入
   	    noticeParent(2, true);
    },time*1000);

	if (window.ActiveXObject) {		
		try {
			var  AX = new ActiveXObject("Qihoo.QuickLogin.1");
		} catch (ex) {
			noticeParent(2);
		}
	}else if(navigator.mimeTypes["application/mozilla-npqihooquicklogin"]){
		try{
			var AX = document.createElement("embed");
			AX.type = "application/mozilla-npqihooquicklogin";
			AX.style.width = "0px";
			AX.style.height = "0px";
			document.body.appendChild(AX);
			 
		}catch(ex){
			noticeParent(2);
		}
	
	}else{
		noticeParent(2);
	}

	if(us==1){
		getUserStatus();
		return;
	}
	
	/**ID选择器**/
	function g(id){
		return document.getElementById(id);
	}
	
	/**class选择器**/
	function getElementsByClassName(n) {
		var classElements = [],allElements = document.getElementsByTagName('*');
		for (var i=0; i< allElements.length; i++ ) {
			if (allElements[i].className == n ) {
				classElements[classElements.length] = allElements[i];
			}
		}
		return classElements;
	}

	/******获得登录列表********/
	function getUser() {
		try{	
		 	AX && AX.GetUserList(renderHtml);
		 }catch(ex){
			noticeParent(2);
		}
	}

	function getUserStatus(){
		try{
			if(AX){
				AX.GetUserList(function(data){
					data = new Function('return ('+ data +');')();
					data = data||[];
					g('ifr_getmsg').src = nextUrl +"?fun=parent.parent."+func+"&us="+data.length;
				})
			}else{
				g('ifr_getmsg').src = nextUrl +"?fun=parent.parent."+func+"&us=0";
			}
		}catch(ex){
			noticeParent(2, true);
		}
	}
	
	function setDomain(){
		//游戏子域名
		var domainStr = ['rd', 'wan', 'game', 'kaifang'].join(',');
		domain_list = (domain_list||('1360,360,qihoo,woxihuan,yunpan,360pay,so,360kan,leidian,qikoo')).split(',');
		if(domain_list.length==2 && domain_list[1]=="nc"){
			primaryStation = true;
			return;
		}
		var suffix = '.com';
		forEach(domain_list,function(item){
			suffix = item=="yunpan" || item=="360pay" || item=="360" ? ".cn": (item == "5kong" ? ".tv" : ".com");

			//专门处理1360.com的问题
			if((item.indexOf('1360') > -1 || domainStr.indexOf(item) > -1) && item != "1360") {
				item = item.replace(/\d{1,}/ig, "") + ".1360";
			}
			domainList.push(requestScema+"://login."+item+suffix);
		});
	
	}

	


	/******获得key********/
	function getOneKey(ret) {
		if(!ret){
			showMsg(acc_msg);
			return;
		}
		loadJsonp(quickUrl+"&requestScema="+requestScema+"&key="+encodeURIComponent(ret)+"&isKeepAlive="+iskeepalive+"&src="+src,
			function(data) {
				if (data.errno == 0) {
					if(primaryStation){
						flag_skip && noticeParent(0);
					}else{
						rd = data.rd;
						
						loadJs(domainList[tempDomainNum]+ "/?o=sso&m=setcookie&requestScema="+requestScema+"&func=rdCallBack&" + "s=" + data.rd);
					}
				
				}else {
					showMsg(decodeURIComponent(data.errmsg))
				}
			})
	}

	function showMsg(msg){	
		clk_flag = true;
		clearTimeout(loginTimeoutHandler);
		
		g('q_login_logining').style.display ="none";
		g('q_login_tips').style.visibility = "visible";
		g('q_login_tips').innerHTML = msg;
	}
	function loginWeb(){
		loadJs(requestScema+"://login.360.cn/?o=sso&m=getRd&requestScema="+requestScema+"&func=rdCallBack&s="+Math.random());
	}
	/********登录*********/
	window.clickLogin =function(obj) {
		if(!cookieEnabled)return;
		if(!clk_flag)return;
		clk_flag = false;
		flag_skip = true;
		tempDomainNum = 0;
		loginTimeoutHandler = setTimeout(function(){
			flag_skip = false;
			showMsg('登录超时，请稍候重试。');
		},16000);		
		g('q_login_tips').style.visibility ="hidden";
		g('q_login_logining').style.display= "block";
		var qid = obj.getAttribute('data-qid');
		if(web_qid ==qid){
			loginWeb();
		}else{
			try{
				AX && AX.GetCode(qid, getOneKey);
			}catch(ex){
				noticeParent(2);
			}
		}
		
	}
	window.rdCallBack = function(ret){
		if(ret.errno==0 || ret.rd){
			if(ret.rd){
				rd = ret.rd;
			}
			tempDomainNum ++;
			if(tempDomainNum == domainList.length){
				flag_skip && noticeParent(0);
			}else{
		    	if(flag_skip ){
			    	loadJs(domainList[tempDomainNum]+ "/?o=sso&m=setcookie&requestScema="+requestScema+"&func=rdCallBack&" + "s=" + rd);
			    }
			}
		}else{
			showMsg(decodeURIComponent(ret.errmsg));	
		}
	
	}
	window.moveUnit = function(dire){
		start(dire);
	}
	
	/**
	 * 计算字符串长度（中英文）
	 * @param {String} str [需计算长度的字符串]
	 * @returns {Number} [返回字符串长度]  
	 */
	function strLen(str){
		var len = 0;
		for (var i=0; i<str.length; i++) { 
			var c = str.charCodeAt(i); 
			//单字节加1 
			if ((c >= 0x0001 && c <= 0x007e) || (0xff60<=c && c<=0xff9f)) { 
				len++; 
			}else { 
				len+=2; 
			} 
		} 
		return len;
	}
	
	/**
	 * 字符串截取（中英文）
	 * @param {String} str [需要截取的字符串]
	 * @param {Number} len [汉字的长度 一个字=两个字符]
	 * @returns {String} [截取后的字符串]
	 */
	function cutStr(str, len){
        var char_length = 0;
        for (var i = 0; i < str.length; i++){
            var son_str = str.charAt(i);
            encodeURI(son_str).length > 2 ? char_length += 1 : char_length += 0.5;
            if (char_length >= len){
                var sub_len = char_length == len ? i+1 : i;
                return str.substr(0, sub_len);
                break;
            }
        }
    }
	/*获取当前样式*/
	function getCurrentStyle(node, attr) {
		if(window.getComputedStyle) {
			return window.getComputedStyle(node, null)[attr];
		}else{
			return node.currentStyle[attr];
		}
	}
	
	window.setQuickBtnQid = function(obj) {
		var qid = obj.value;
		g('quickLoginBtn').setAttribute('data-qid', qid);
	}
	
	function renderHtml(userlist) {
		userlist  = new Function('return (' + userlist +');')();
		if (userlist&& userlist.length > 0) {

			number = userlist.length;
			var userHtml = [],
				qidlist = [];
			
			if(web_qid){
				qidlist.push(web_qid);
				userlist.unshift({'qid':web_qid})
			}
			for(var n in userlist){
				if(web_qid!==userlist[n].qid){
					qidlist.push(userlist[n].qid);
				}
				
			}
		
			loadJs(imgUrl+ "&requestScema="+requestScema+"&qid_list="+qidlist.join(',')+"&head_type=b&func=window.renderImg&_t="+Math.random());
			
			window.renderImg = function (data){
				clearTimeout(timeoutHandler);
				if(data.errno!=0){
					noticeParent(2);
					return;
				
				}else{
					var allimg = data.img_arr;
					for ( var i in userlist) {	
						try{
							var obj = userlist[i],
								sUserName = '360用户',
								uname = /(360U)/ig.test(obj.nickname) ? (obj.username|| obj.nickname ) :obj.nickname|| obj.username,
								userName =decodeURIComponent(uname || obj.email||'360用户');
							sUserName = userName = accountName(obj.type,userName);
						}catch(ex){}
						if(strLen(userName)>16){
							sUserName = cutStr(userName,8);
						}
						if(displayType == "text") {
							g("checkboxLoginbtn").style.marginLeft = "110px";
							if(userlist.length  == 1) {
								userHtml.push('<div class="user-text-list">'+sUserName+'</div>');
								g('quickLoginBtn').setAttribute('data-qid', obj.qid);
							}else {
								if(i == 0){
									userHtml.push('<div class="user-text-list"><input onclick="setQuickBtnQid(this);" id="userRadio'+obj.qid+'" type="radio" name="user" value="'+obj.qid+'" checked hidefocus=true><label for="userRadio'+obj.qid+'"> '+sUserName+'</label></div>');
									g('quickLoginBtn').setAttribute('data-qid', obj.qid);
								}else {
									userHtml.push('<div class="user-text-list"><input onclick="setQuickBtnQid(this);" type="radio" name="user" id="userRadio'+obj.qid+'" value="'+obj.qid+'" hidefocus=true><label for="userRadio'+obj.qid+'"> '+sUserName+'</label></div>');
								}
							}
						}else if(displayType == "picture"){
							userHtml.push('<div class="quickLoginImg">');
							userHtml.push('<a hidefocus="true" text="点击头像登录" data-qid ="'+obj.qid+'" onclick="clickLogin(this);" href="javascript:void(0)">');
							userHtml.push('<img src="'+allimg[obj.qid].img_url+'" height="104" width="104" />');
							userHtml.push('<span class="headImg-above-tips">');
							userHtml.push('<span data-qid ="'+obj.qid+'" onclick="clickLogin(this);">登录</span>');
							userHtml.push('</span></a><p  title="'+userName+'">'+sUserName+'</p></div>');
						}else if(displayType == "newpic"){
							userHtml.push('<div class="quickLoginImg">');
							userHtml.push('<a hidefocus="true" text="点击头像登录" data-qid ="'+obj.qid+'" onclick="clickLogin(this);" href="javascript:void(0)">');
							userHtml.push('<img src="'+allimg[obj.qid].img_url+'" height="104" width="104" />');
							userHtml.push('<span class="headImg-above-tips">');
							userHtml.push('<span data-qid ="'+obj.qid+'" onclick="clickLogin(this);">登录</span>');
							userHtml.push('</span></a><p  title="'+userName+'">'+sUserName+'</p></div>');
						}
					}
					g('loginUserList').innerHTML = userHtml.join('');
					g('ifr_getmsg').src= nextUrl +"?fun=parent.parent.QHPass.ptLogin&s=1";
					if(displayType == "newpic"){
						qidNode = getElementsByClassName("quickLoginImg")[0].getElementsByTagName("a")[0];
						qid = qidNode.getAttribute("data-qid");
						g("newPicLoginBtn").setAttribute('data-qid', qid);
					}
					if(displayType != "text") {
						var imgEl = getElementsByClassName('quickLoginImg')[0];
						var divWidth = getCurrentStyle(imgEl, 'width').replace('px', '')*1;
						var marginRight = getCurrentStyle(imgEl, 'marginRight').replace('px', '')*1;
						var marginLeft = getCurrentStyle(imgEl, 'marginLeft').replace('px', '')*1;
						var width = divWidth + marginRight + marginLeft;
						g('userPicListOuter').style.width = Math.min(custUserNum, number)*width + 'px';
						tempN = number;
						oneUnit = width;
						switch(custUserNum) {
							case 1:
								if(number>1){
									g('right_dire').style.visibility ="visible";
									g('right_dire').className = 'arr arr-next arr-next-1';
									g('left_dire').className = 'arr arr-prev arr-prev-1';
								}
								break;
							case 2:
								if(number>2){
									g('right_dire').style.visibility ="visible";
									g('right_dire').className = 'arr arr-next arr-next-2';
									g('left_dire').className = 'arr arr-prev arr-prev-2';
								}
								break;
							default:
								if(number>3){
									g('right_dire').style.visibility ="visible";
								}
								break;
						}
					}
				}
			}

		} else {
			noticeParent(2);
		}

	}
    /******对用户名进行处理******/
	function accountName(type,uname){
		var _userName = "";
		switch(type){
			case "sinaweibo":
				_userName = "新浪微博-" +uname;
				break;
			case "renren":
				_userName = "人人-" +uname;
				break;
			case "fetion":
				_userName = "飞信-" +uname;
				break;
			default:
				_userName  = uname;
				break;
		}
		return _userName;
	}

	function animFun(time) {
		var per = Math.min(0.5, (new Date - startTime) / dur);
		var leftDistance,nodeIndex,qidNode,qid;
		if(per >= 0.5) {
			if(displayType == "newpic"){
				leftDistance = parseInt(g("loginUserList").style.marginLeft);
				nodeIndex = leftDistance > 0 ? Math.floor(leftDistance/120) : Math.floor(-leftDistance/120);
				qidNode = getElementsByClassName("quickLoginImg")[nodeIndex].getElementsByTagName("a")[0];
				qid = qidNode.getAttribute("data-qid");
				g("newPicLoginBtn").setAttribute('data-qid', qid);

			}
			clearTimeout(timerId);
			setSlider();
		} else {
			if(dire=="left"){
				obj.style.marginLeft = mleft + Math.round(oneUnit*per*2) +"px";
			}else{
				obj.style.marginLeft = mleft + Math.round((-oneUnit)*per*2) +"px";
			}
		}
	}

	function setSlider(){
		s_flag = false;
		if(dire=="left"){
			number +=1;
		}else{
			number -=1;
		}
		if(number==tempN){
			g('right_dire').style.visibility = "visible";
			g('left_dire').style.visibility = "hidden";
		}else if (number == custUserNum){
			g('left_dire').style.visibility = "visible";
			g('right_dire').style.visibility = "hidden";
		}else if(number>0 && number < tempN){
			g('left_dire').style.visibility = "visible";
			g('right_dire').style.visibility = "visible";
		}
	}
	 
	function start(fx) {
		if(s_flag)return;
		g('q_login_tips').innerHTML = "";
		s_flag = true;
		dire = fx;
		mleft = parseInt(obj.style.marginLeft||0);
	    startTime = new Date;
		timerId = setInterval(animFun, frameTime);
	}
	
	
	/*****加载****/
	setDomain();
	getUser();
}());
